<template>
  <view class="container">
    <uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
      @clickItem="onClickItem" />
    <view v-if="currentIndex === 0">
      <view style="padding-top: 10px;"></view>
      <uni-forms ref="baseForm" :modelValue="liuzhuanForm" labelPosition="left" border labelWidth="100px">
        <view style="padding-top: 10px;"></view>

        <uni-forms-item label="发起部门" required>
          <uni-easyinput type="text" v-model="liuzhuanForm.danwei" />
        </uni-forms-item>

        <uni-forms-item label="发文时间" required>
          <uni-datetime-picker @click="chuanci()" @change="chuanci2" @maskClick="chuanci2()" type="date"
            return-type="string" v-model="liuzhuanForm.chengwenDate" />
        </uni-forms-item>
        <!-- <uni-forms-item label="收文编号">
          <uni-easyinput type="text" v-model="liuzhuanForm.wenhao" />
        </uni-forms-item>
        <uni-forms-item label="收文字号">
          <uni-easyinput type="text" v-model="liuzhuanForm.zihao" />
        </uni-forms-item> -->

        <uni-forms-item label="标题" required>
          <uni-easyinput @change="chuanci2" @input="chuanci2" v-model="liuzhuanForm.biaoti" />
        </uni-forms-item>

        <uni-forms-item label="内容摘要" required>
          <uni-easyinput type="textarea" v-model="liuzhuanForm.zhaiyao" />
        </uni-forms-item>

        <!-- 附件模块 -->
        <uni-forms-item label="附件" style="height: 80rpx;margin-top: 120rpx; position: relative;">
          <lsj-upload v-show="liuzhuanForm.accessoryBeans.length == 0"
            style="position:absolute !important;  z-index: 10; !important" ref="lsjUpload" childId="upload1"
            :size="uploadconfig3.size" :instantly="uploadconfig3.instantly" :formats="uploadconfig3.formats"
            :option="option" @change="onChange" @uploadEnd="onuploadEnd" @fail="failFile">
            <view style="width: 100%;text-align: right;color: #3C95FF;" @click="fuckyou">
              <i class="iconfont icon-24gf-folderOpen" style="color: #3C95FF;"></i>
              上传附件
            </view>
          </lsj-upload>
        </uni-forms-item>
        <view v-if="liuzhuanForm.accessoryBeans.length">
          <view class="file_list" v-for="(item, index) in liuzhuanForm.accessoryBeans" :key="index">
            <!--  @click="prevFileClick(item.url, item.name)" -->

            <view style="display: flex; align-items: center; color: #3b95ff">
              <view @click="prevFileClick(item)" class="file_list_item">
                <view>
                  <i class="iconfont icon-24gf-folderOpen" style="color: #3c95ff"></i>
                  {{ item.name }}
                </view>
              </view>
              <view class="iconfont icon-close" style="color: #e86565;margin-left:5px" @click="delFile(index)"></view>
            </view>
          </view>
        </view>

        <!-- 选人模块 -->
        <uni-forms-item label="审核人" required></uni-forms-item>
        <view v-for="(item, idx) in liuzhuanForm.auditors" :key="idx">
          <uni-row>
            <uni-col :span="10">
              <view v-if="idx > 0" class="step-arrow">
                <uni-icons type="bottom" size="mini" color="#a5eaff"></uni-icons>
              </view>
            </uni-col>
          </uni-row>
          <view class="step">
            <uni-row>
              <uni-col :span="10">
                <view class="step-info-left">{{ item.stepName }}</view>
              </uni-col>
              <uni-col :span="14">
                <view class="step-info-right">{{ item.stepName == '分管领导' ? '待选择' : item.name }}</view>
              </uni-col>
            </uni-row>
          </view>
        </view>

        <view style="padding-top: 30px;"></view>
        <button type="primary" @click="clickApply">提交</button>
      </uni-forms>
    </view>
    <view v-if="currentIndex === 1">
      <view>
        <uni-search-bar v-model="keyword" radius="100" placeholder="输入文件关键字" cancelButton="none" @confirm="search" />
      </view>
      <view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
        <!-- {{item}} -->
        <view class="card" @click="seeDetail(idx)">
          <view class="card-title">
            <uni-row>
              <uni-col :span="20">
                <view class="card-title-left">&nbsp;{{ item.title }}</view>
              </uni-col>
              <uni-col :span="4">
                <view class="card-title-right">
                  <uni-tag text="审核" size="mini" type="warning" v-if="item.approvalState === 0"></uni-tag>
                  <uni-tag text="通过" size="mini" type="primary" v-if="item.approvalState === 1"></uni-tag>
                  <uni-tag text="拒绝" size="mini" type="error" v-if="item.approvalState === 2"></uni-tag>
                  <uni-tag text="撤销" size="default" type="default" v-if="item.approvalState === 3"></uni-tag>
                </view>
              </uni-col>
            </uni-row>
          </view>
          <view class="card-body">
            <view>内容：{{ item.content }}</view>
          </view>
          <view class="card-footer">
            <uni-row>
              <uni-col :span="12">
                <view class="card-footer-left">{{ item.createBy }}</view>
              </uni-col>
              <uni-col :span="12">
                <view class="card-footer-right">{{ getFormatedTimeStr(item.createTime, "YYYY-MM-DD hh:mm:ss") }}</view>
              </uni-col>
            </uni-row>
          </view>
        </view>
      </view>
      <uni-load-more :status="moreStatus"></uni-load-more>
    </view>
  </view>
</template>

<script>
import moment from "moment";
import { websock } from "../../net/websock";
import {
  getDateFn, // 获取当前时间 年月日
} from "../../utils/fun.js";
import {
  prevFile // 预览文件
} from "../../utils/preview.js";
import { addFawen, getXinjianList } from "../../net/xinjianfawen";
import { uploadconfig3 } from "../../const";
import { quchongAuditors } from "../../utils/util";

export default {
  data() {
    return {
      // 上传参数部分没有事情不要乱动
      uploadconfig3,
      option: {
        url: uploadconfig3.url,
        name: "file",
        header: { Authorization: uni.getStorageSync("token"), platform: 'APP' },
        formData: {}
      },
      total: 1, //当前页
      pageSize: 10,
      pageNum: 1,
      formats: uploadconfig3.formats,
      instantly: uploadconfig3.instantly,
      size: uploadconfig3.size,
      // files: new Map(),
      // 上传参数部分没有事情不要乱动
      items: ["发起提交", "查看数据"],
      currentIndex: 0,
      moreStatus: "more",
      applyRecord: [],
      keyword: "",
      suffix: "",

      files: new Map(),
      liuzhuanForm: {
        bianhao: "",
        danwei: "",
        zhaiyao: "",
        biaoti: "",
        chengwenDate: "",
        readers: [],
        accessoryBeans: [],
        auditors: []
      }
    };
  },
  async onLoad() {
    try {
      this.userInfo = await websock.getUserInfo();
      console.log("user info", this.userInfo.uid);
    } catch (err) {
      console.error(err);
    }
  },
  async onReady() {
    // this.getNewestRecord();
    let auditors = await websock.getAuditors({ typ: 24 });
    console.log(auditors);
    quchongAuditors(auditors);
    this.liuzhuanForm.auditors = auditors;
    console.log(this.liuzhuanForm.auditors);
    this.getNewestRecord();
    this.liuzhuanForm.chengwenDate = getDateFn(this.liuzhuanForm.chengwenDate);
  },
  // 下拉刷新，获取最新的数据
  onPullDownRefresh() {
    if (this.currentIndex == 0) {
      uni.stopPullDownRefresh();
    } else {
      this.pageNum = 1;
      this.getNewestRecord();
    }
  },
  // 上拉刷新，获取历史数据
  onReachBottom() {
    if (this.currentIndex == 1) {
      if (this.moreStatus == "more") {
        uni.showLoading({
          title: "加载中"
        });
        this.pageNum += 1;
        this.getOlderRecord();
      }
    }
  },
  methods: {
    // 预览上传的文件
    prevFileClick(url, name) {
      prevFile(url, name);
    },
    // 删除附件
    delFile() {
      for (let i = 0; i < this.liuzhuanForm.accessoryBeans.length; i++) {
        this.liuzhuanForm.accessoryBeans.splice(i, 1);
      }
      this.fuckyou();
    },
    // 附件上传恶心的代码块-------------------------------------------------------------
    // 某文件上传结束回调(成功失败都回调)
    onuploadEnd(item) {
      console.log(item);
      // let files = new Map();
      let res = JSON.parse(item.responseText);
      uni.hideLoading();
      if (res.code === 0) {
        console.log(res);
        this.liuzhuanForm.accessoryBeans.push({
          url: res.data.url,
          name: res.data.fileName
        });
        this.suffix = res.data.suffix;
      }
      this.$forceUpdate();
    },
    // 文件选择回调
    onChange(files) {
      uni.showLoading({
        title: "上传中……"
      });
      this.files = files; // 更新选择的文件
      this.$forceUpdate(); // 强制更新视图
    },
    failFile() {
      uni.hideLoading();
    },
    // 穿刺一击让他们的遮罩层消失
    chuanci() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
    },
    // 穿刺一击让他们的遮罩层消失
    chuanci2() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
    },
    // 强制重置附件按钮,万一出意外点2次按钮至少可以进去
    fuckyou() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
    },
    // 附件上传恶心的代码块-------------------------------------------------------------
    // 获取最新的通知
    async getNewestRecord() {
      try {
        if (this.applyRecord.length == 0) {
          let res = await getXinjianList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            pageSize: 10,
            title: this.keyword
          });
          uni.hideLoading();
          uni.stopPullDownRefresh();
          this.total = res.total;
          this.applyRecord = [...res.data, ...this.applyRecord];
        } else {
          let res = await getXinjianList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            // greaterThan: this.applyRecord[0].id,
            pageSize: 10,
            title: this.keyword
          });
          uni.hideLoading();
          uni.stopPullDownRefresh();
          this.applyRecord = [...res.data, ...this.applyRecord];
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 获取老的数据
    async getOlderRecord() {
      this.moreStatus = "loading";
      try {
        if (this.applyRecord.length == 0) {
          let res = await getXinjianList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            title: this.keyword
          });

          this.applyRecord = this.applyRecord.concat(res.data);
          if (res.data.length < 10) {
            this.moreStatus = "noMore";
          } else {
            this.moreStatus = "more";
          }
        } else {
          let res = await getXinjianList({
            uid: this.userInfo.uid,
            pageNum: this.pageNum,
            // lessThan: this.applyRecord[this.applyRecord.length - 1].id,
            pageSize: this.pageSize,
            title: this.keyword
          });

          this.applyRecord = this.applyRecord.concat(res.data);
          if (res.data.length < 10) {
            this.moreStatus = "noMore";
          } else {
            this.moreStatus = "more";
          }
        }
      } catch (e) {
        uni.showToast({
          title: e.message
        });
      }
    },

    onClickItem(e) {
      console.log(e);
      if (this.currentIndex !== e.currentIndex) {
        this.currentIndex = e.currentIndex;
        // if (this.currentIndex == 1) {
        //   this.getNewestRecord();
        // }
      }
    },
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "MM-DD HH:mm:ss") {
      return moment(stamp).format(str);
    },
    async clickApply() {
      if (!this.liuzhuanForm.danwei)
        return uni.showToast({
          title: "请输入发起部门",
          icon: "none"
        });
      if (!this.liuzhuanForm.biaoti)
        return uni.showToast({
          title: "请输入标题",
          icon: "none"
        });
      if (!this.liuzhuanForm.chengwenDate)
        return uni.showToast({
          title: "请选择发文时间",
          icon: "none"
        });
      if (!this.liuzhuanForm.zhaiyao)
        return uni.showToast({
          title: "请输入内容摘要",
          icon: "none"
        });

      if (this.liuzhuanForm.auditors.length == 0)
        return uni.showToast({
          title: "请选择审核人",
          icon: "none"
        });

      if (this.liuzhuanForm.accessoryBeans.length == 0)
        return uni.showToast({
          title: "请添加附件",
          icon: "none"
        });

      let auditors = [];
      for (let i = 0; i != this.liuzhuanForm.auditors.length; i++) {
        auditors.push({
          ts: "",
          sta: 0,
          msg: "",
          uid: this.liuzhuanForm.auditors[i].uid,
          name: this.liuzhuanForm.auditors[i].name,
          signimg: "",
          stepName:
            this.liuzhuanForm.auditors[i].stepName ||
            this.liuzhuanForm.auditors[i].positionName
        });
      }
      let OldObject = auditors.reduce((o, n, i) => {
        o["auditor" + i] = {
          ts: "",
          msg: "",
          sta: 0,
          signimg: n.signimg,
          uid: n.uid,
          stepName: n.stepName,
          name: n.name
        };
        return o;
      }, {});
      const params = {
        receiveUnit: this.liuzhuanForm.danwei,
        title: this.liuzhuanForm.biaoti,
        receiveData: this.liuzhuanForm.chengwenDate,
        content: this.liuzhuanForm.zhaiyao,
        // url: this.liuzhuanForm.pics,
        accessoryBeans: this.liuzhuanForm.accessoryBeans || [],
        // readers,
        approvalProcessDataBeanMap: OldObject
      };
      try {
        await addFawen(params);
        setTimeout(
          () =>
            uni.navigateBack({
              delta: 1
            }),
          uni.showToast({
            title: "操作成功",
            icon: "success"
          }),

          1000
        );
        this.liuzhuanForm = {
          danwei: "",
          biaoti: "",
          chengwenDate: "",
          readers: [],
          attaches: [],
          auditors: [],
          accessoryBeans: []
        };

        this.currentIndex = 1;
        this.getNewestRecord();
      } catch (err) {
        uni.showToast({
          title: err.message || "error"
        });
      }
    },
    // async revertApply(idx) {
    //   try {
    //     await websock.revertxinjianFawen({
    //       id: this.applyRecord[idx].id
    //     });
    //     this.applyRecord[idx].sta = 4;
    //   } catch (err) {
    //     uni.showToast({
    //       title: err.message || "error"
    //     });
    //   }
    // },
    seeDetail(idx) {
      console.log(idx);
      uni.navigateTo({
        url: `/pages/task/xinjianfawenDetail?content=${JSON.stringify(
          this.applyRecord[idx]
        )}&itemss=${this.currentIndex}`
      });
    },
    search() {
      this.applyRecord = [];
      this.getNewestRecord();
    }
  }
};
</script>

<style>
@import "../common/common.css";

/* 封面上传控件 */
::v-deep .file-picker__box {
  position: absolute !important;
  right: 0 !important;
  width: 200rpx !important;
  height: 132rpx !important;
}

::v-deep .file-picker__box-content {
  border: none !important;
}
</style>
